import axios from 'axios'
export default {
    namespaced:true,
    state: () => ({
        cart:[]
    }),
    mutations: {
        updateCart(state,payload) { 
            state.cart=payload
        },
        updateStateCart(state, payload) { 
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_state=payload.value
        },
        updateStateCount(state, payload) { 
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_count=payload.value
        },
        updateStateAll(state,val) { 
            // console.log(val);
            state.cart.forEach(item=>item.goods_state=val)
        }

    },
    actions: {
       async getCartList(context) { 
            let res = await axios.get('https://www.escook.cn/api/cart')
            context.commit('updateCart',res.data.list)
        }
    },
    getters: {
        allPrice(state) { 
           return state.cart.filter(item => item.goods_state).reduce((sum, item) => { 
              return sum += item.goods_count * item.goods_price
           }, 0)
        },
        allCount(state) { 
            let newCart = state.cart.filter(item => item.goods_state)
            return newCart.reduce((sum, item) => {
              return sum+=item.goods_count
             },0)
        }
    }
}